package com.soso.base.util.search;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlTagExcludeUtil {
	private static Map<String,String> htmlTags=new HashMap<String,String>();
	static{
		htmlTags.put("nbsp", "&nbsp;");
		htmlTags.put("space", " ");
		htmlTags.put("enter", "\r\n");
		htmlTags.put("tab", "\t");
	}
	public static void main(String[] args){
		String html="< div id=\"111\"><img src=''/><div id=\"22\">test1</div>test2<div>test3<div>test4</div><input/><p></p><span></span></div></div>";
		html=HtmlTagExcludeUtil.excludeHtmlTag2(html, "img");
		System.out.println(html);
		html=HtmlTagExcludeUtil.excludeHtmlTag2(html, "div");
		System.out.println(html);
	}
	public static String exclude(String html,String tag){
		if(htmlTags.containsKey(tag)){
			html=html.replaceAll(htmlTags.get(tag), "");
		}
		return excludeHtmlTag2(html,tag);
	}
	/**
	 * @param html "<b>test</b><b>test</b>"
	 * @param tag  
	 * @return
	 */
	public static String excludeHtmlTag1(String html,String tag){
		String regex="(.*)<"+tag+".*?>(.*?)</"+tag+">(.*)";
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher m = p.matcher(html);
		if(m.find()) {
			html=m.group(1)+m.group(2)+m.group(3);
			return excludeHtmlTag1(html,tag);
		}else{
			return html;
		}
			
	}
	/**
	 * 
	 * @param html "<br>" or "<img src=''/>"
	 * @param tag
	 * @return
	 */
	public static String excludeHtmlTag2(String html,String tag) {
		String regex="</?\\s*?"+tag+".*?>";
		html=Pattern.compile(regex,Pattern.DOTALL).matcher(html).replaceAll("");
		return html;
	}

}
